# -*- coding:utf-8 -*-
import sys
import json
from decimal import Decimal
import MySQLdb
def default(obj):
    if isinstance(obj, Decimal):
        return str(obj)
    raise TypeError
#连接数据库
dbstr=sys.argv[1]
city=sys.argv[2]
tbl = sys.argv[3]
print dbstr
#conn=MySQLdb.connect(host='rds1tu038044m8zub4o7.mysql.rds.aliyuncs.com',user='zhuge',passwd='zhuge1116',db=dbstr,port=3306,charset="utf8")
#conn=MySQLdb.connect(host='182.92.96.120',user='zhuge',passwd='zhuge1116',db=dbstr,port=3306,charset="utf8")
conn=MySQLdb.connect(host='101.200.81.152',user='zhuge',passwd='zhuge1116',db=dbstr,port=3307,charset="utf8")
cur = conn.cursor()
cur.execute('select count(*) from %s'% tbl)
#获取数据库中记录总条数
count_all=cur.fetchone()[0]
print count_all
#每一次获取1000条数据
page_count=1000;
cur = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
#打开文件，准备写
filename = "%s/%s" % (city, tbl)
file = open(filename, "w")
#for($i=0;$i<=($sell_gov_count/$page_count);$i++)
j=0
page_num =  count_all/page_count + 1
for i in range(0,page_num):
    if (tbl == 'borough'):
    	query = 'select borough_name, id, cityarea_id, cityarea2_id from borough limit %d,%d'%(i*page_count,page_count)
    elif (tbl == 'broker_check'):
	query = 'select phone, id from broker_check limit %d,%d'%(i*page_count,page_count)
    elif (tbl == 'subwaytoborough'):
        query = 'select bid, id from subwaytoborough limit %d,%d'%(i*page_count,page_count)
    elif (tbl == 'borough_info'):
    	query = 'select borough.id, borough_shop, borough_hospital, nursery_school, middle_school, elementary_school, borough_bus, borough_dining from borough left join borough_info on borough.id = borough_info.id limit %d,%d'%(i*page_count,page_count)
    else:
        query = 'select * from %s limit %d,%d'%(tbl,i*page_count,page_count)
    cur.execute(query)
    
    results=cur.fetchall()
    for row in results:
        j = j+1;
	#file.write(json.dumps(row,default=default))
	#file.write("\n")
        file.write(json.dumps(row,default=default))
	file.write("\n")
file.close()
